package com.atguigu.crowd.funding.exception;

import com.atguigu.crowd.funding.entity.ResultEntity;
import com.atguigu.crowd.funding.util.CrowdFundingConstant;
import com.atguigu.crowd.funding.util.CrowdFundingUtils;
import com.google.gson.Gson;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author hftang
 * @date 2019-10-23 14:45
 * @desc
 */

@ControllerAdvice
public class CrowdFundingExceptionResolever {


    @ExceptionHandler(value = Exception.class)
    public ModelAndView handlerException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 1.对当前请求进行检查
        boolean checkAsyncRequestResult = CrowdFundingUtils.checkAsyncRequest(request);
        // 2.如果是异步请求
        if (checkAsyncRequestResult) {

            // 根据异常类型在常量中的映射，使用比较友好的文字显示错误提示消息
            String exceptionClassName = e.getClass().getName();

            String message = CrowdFundingConstant.EXCEPTION_MESSAGE_MAP.get(exceptionClassName);

            if (message == null) {
                message = "系统未知错误";
            }

            // 3.创建ResultEntity对象
            ResultEntity<String> resultEntity = ResultEntity.failed(ResultEntity.NO_DATA, message);


            // 3.创建ResultEntity对象
//            ResultEntity<String> resultEntity = ResultEntity.failed(ResultEntity.NO_DATA, e.getMessage());

            // 4.将resultEntity转换为JSON格式
            Gson gson = new Gson();
            String json = gson.toJson(resultEntity);

            // 5.将json作为响应数据返回给浏览器
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(json);

            return null;
        }


        ModelAndView modelAndView = new ModelAndView();

        modelAndView.addObject("exception", e);
        modelAndView.setViewName("system-error");


        return modelAndView;


    }
}
